package com.jy.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jy.common.enums.ResponseWrapper;
import com.jy.common.model.dyamic.*;
import com.jy.common.tool.CommonTool;
import com.jy.common.tool.GaoDeTool;
import com.jy.common.tool.ToolForDateTime;
import com.jy.entity.*;
import com.jy.mapper.*;
import com.jy.service.DynamicService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 动态表（用户发的动态：包括笔记，视频，此刻） 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2024-11-13
 */
@Service
public class DynamicServiceImpl extends ServiceImpl<DynamicMapper, Dynamic> implements DynamicService {

    private final DynamicMapper dynamicMapper;


    private final UserMapper userMapper;

    private final UserFollowMapper userFollowMapper;

    private final ThumbsUpMapper thumbsUpMapper;

    private final TopicUserMapper topicUserMapper;

    private final TopicMapper topicMapper;

    private final CommentMapper commentMapper;

    private final CollectMapper collectMapper;



    public DynamicServiceImpl(DynamicMapper dynamicMapper, UserMapper userMapper, UserFollowMapper userFollowMapper, ThumbsUpMapper thumbsUpMapper, TopicUserMapper topicUserMapper, TopicMapper topicMapper, CommentMapper commentMapper, CollectMapper collectMapper, CardHistoryMapper cardHistoryMapper) {
        this.dynamicMapper = dynamicMapper;
        this.userMapper = userMapper;
        this.userFollowMapper = userFollowMapper;
        this.thumbsUpMapper = thumbsUpMapper;
        this.topicUserMapper = topicUserMapper;
        this.topicMapper = topicMapper;
        this.commentMapper = commentMapper;
        this.collectMapper = collectMapper;
    }

    @Override
    public ResponseWrapper getOnlineConsultantInfoAndUserDynamic(Integer userAid, Integer page, Integer size) {

        // 返回结果
        HashMap<String, Object> result = new HashMap<>();

        // 获取在线顾问信息
//        Dynamic consultant = dynamicMapper.selectOne(new LambdaQueryWrapper<Dynamic>()
//                .eq(Dynamic::getUserAid, 6)
//                .eq(Dynamic::getDynamicType, "系统推荐")
//        );
        User user = userMapper.selectById(6);
        // 数组存放热门信息
//        String[] hotInfos = consultant.getDynamicContent().split("&&&");
//        HashMap<String, Object> consultantInfo = new HashMap<>();
//        consultantInfo.put("reMenHuaTis", hotInfos);
//        consultantInfo.put("name", user.getName());
//        consultantInfo.put("desc", user.getLabelDesc());
//        consultantInfo.put("dynamic_name", consultant.getDynamicName());
//        consultantInfo.put("infoBg", consultant.getDynamicImgs());
//        consultantInfo.put("avatar", user.getAvatar());
//        result.put("consultantInfo", consultantInfo);

        // 获取用户的动态（最多10条）
        User currentLoginUser = userMapper.selectById(userAid);

        Page<Dynamic> dynamics = dynamicMapper.selectPage(new Page<>(page, size), new LambdaQueryWrapper<Dynamic>()
                .ne(Dynamic::getUserAid, 6)
                .ne(Dynamic::getUserAid, 7)
                .eq(Dynamic::getIsRelease,true)
                .eq(Dynamic::getIsDraft,false)
                .orderByDesc(Dynamic::getUpdateTime)
        );
//        List<Dynamic> records;
//        if (dynamics.getRecords().size() == 0){
//            // 说明已经到最后一页并且没有数据可以刷新了，这时候返回来查询第一页
//            records = dynamicMapper.selectPage(new Page<>(1, size), new LambdaQueryWrapper<Dynamic>()
//                    .ne(Dynamic::getUserAid, 6)
//                    .orderByDesc(Dynamic::getCreateTime)
//            ).getRecords();
//        }else {
//            records = dynamics.getRecords();
//        }
        List<Dynamic> records = dynamics.getRecords();
        // 获取当前登录的用户的关注列表
        List<UserFollow> userFollows = userFollowMapper.selectList(new LambdaQueryWrapper<UserFollow>()
                .eq(UserFollow::getFollowerAid, userAid)
        );

        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        for (Dynamic dynamic : records) {
            Map<String, Object> map = new HashMap<>();
            // 发动态的人头像
            User user1 = userMapper.selectById(dynamic.getUserAid());
            map.put("userAid", user1.getAid());
            map.put("userName", user1.getName());
            map.put("avatar", user1.getAvatar());
            map.put("address", dynamic.getReleaseAddress() == null ? "" : dynamic.getReleaseAddress());
            map.put("dynamicAid", dynamic.getAid());
            map.put("contentTilte", dynamic.getDynamicName());
            map.put("contentText", dynamic.getDynamicContent().length() > 45 ? dynamic.getDynamicContent().substring(0,45) + "..." : dynamic.getDynamicContent());
            HashMap<String, Object> imageObj = getStringObjectHashMap(dynamic);
            map.put("imageObj",imageObj);
            if(dynamic.getDynamicImgs() != null){
                String dynamicImgs = dynamic.getDynamicImgs();
                if (dynamicImgs.contains(";")){
                    String[] split = dynamicImgs.split(";");
                    List<String> list = Arrays.asList(split);
                    if (list.size() >= 4){
                        map.put("imgCount",4);
                    }else {
                        map.put("imgCount",1);
                    }
                }else {
                    map.put("imgCount",1);
                }
            }else {
                map.put("imgCount",0);
            }
            if(dynamic.getMedioType().equals("video")){
                map.put("isDynamicImage",false);
                map.put("video",dynamic.getDynamicVideo() == null ? "" : dynamic.getDynamicVideo());
                map.put("poster",(dynamic.getDynamicCover() == null || dynamic.getDynamicCover().equals("")) ? "" : dynamic.getDynamicCover());
            }else {
                map.put("isDynamicImage",true);
                map.put("video","");
                map.put("poster","");
            }
            map.put("fromWhere", "来自TA的动态");
            map.put("commentNum", CommonTool.convertNumberToString(dynamic.getCommentNum()));
            map.put("dianZanNum", CommonTool.convertNumberToString(dynamic.getDianZanNum()));
            // 当前用户是否关注了这条动态的作者
            boolean isFollower = false;
            for (UserFollow userFollow : userFollows) {
                if (userFollow.getFolloweredAid().equals(dynamic.getUserAid())) {
                    isFollower = true;
                    break;
                }
            }
            map.put("isFollower", isFollower);
            // 是否点赞
            ThumbsUp thumbsup = thumbsUpMapper.selectOne(new LambdaQueryWrapper<ThumbsUp>()
                    .eq(ThumbsUp::getThumbsUpUserAid, userAid)
                    .eq(ThumbsUp::getThumbsUpedAid, dynamic.getAid())
                    .eq(ThumbsUp::getType, "动态")
            );
            if (thumbsup != null) {
                map.put("handType", thumbsup.getHandType());
                map.put("thumbsupColor", thumbsup.getHandColor());
                map.put("isThumbsUp", true);
            } else {
                map.put("handType", "heart-filled");
                map.put("thumbsupColor", "#fff");
                map.put("isThumbsUp", false);
            }
            maps.add(map);
        }
        result.put("userListDongTais", maps);
        return ResponseWrapper.markSuccess(result);
    }

    private static HashMap<String, Object> getStringObjectHashMap(Dynamic dynamic) {
        HashMap<String, Object> imageObj = new HashMap<>();
        List<String> imgList = new ArrayList<>();
        if (dynamic.getDynamicImgs()!= null) {
            String[] split = dynamic.getDynamicImgs().split(";");
            Collections.addAll(imgList, split);
        }
        // 确保imgList长度至少为4，不足则用空字符串填充
        while (imgList.size() < 4) {
            imgList.add("");
        }
        imageObj.put("firstImg", imgList.get(0));
        imageObj.put("secondImg", imgList.get(1));
        imageObj.put("thirdImg", imgList.get(2));
        imageObj.put("fourthImg", imgList.get(3));
        return imageObj;
    }

    @Override
    public ResponseWrapper getCampingDynamicList(Integer currentLoginUserAid,String travelMode) {

        // 获取露营动态列表（按照发布时间获取最近最新的点赞量最多的倒序，获取20条）
        List<Dynamic> campingList = dynamicMapper.selectList(new LambdaQueryWrapper<Dynamic>()
                .eq(Dynamic::getDynamicType, "露营")
                .eq(Dynamic::getDynamicArea, travelMode.equals("境内游") ? "国内" : "国外")
                .ne(Dynamic::getUserAid, 6)
                .ne(Dynamic::getUserAid, 7)
                .orderByDesc(Dynamic::getUpdateTime)
                .orderByDesc(Dynamic::getDianZanNum)
                .eq(Dynamic::getIsDraft,false)
                .eq(Dynamic::getIsRelease,true)
                .last("limit 20")
        );

        // 返回数据
        return getDynamicListFunc(campingList,currentLoginUserAid);
    }

    private ResponseWrapper getDynamicListFunc(List<Dynamic> campingList, Integer currentLoginUserAid) {

        ArrayList<HashMap<String, Object>> result = new ArrayList<>();
        for (Dynamic dynamic : campingList) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("aid", dynamic.getAid());
            String dynamicVideo = dynamic.getDynamicVideo()!= null? dynamic.getDynamicVideo() : "";
            String dynamicCover = dynamic.getDynamicCover()!= null? dynamic.getDynamicCover() : "";

            if (dynamic.getMedioType().equals("image")) {
                if(dynamic.getDynamicImgs().equals("") || dynamic.getDynamicImgs() == null){
                    map.put("url", "");
                }else {
                    String dynamicImgs = dynamic.getDynamicImgs();
                    if(dynamicImgs.contains(";")){
                        String[] split = dynamicImgs.split(";");
                        map.put("url", split[0]);
                    }else {
                        map.put("url", dynamicImgs);
                    }
                }
            } else {
                map.put("url", dynamicVideo == null ? "" : dynamicVideo);
            }
//            System.out.println("当前登录用户：" + currentLoginUserAid);
            // 当前登录用户是否点赞这篇动态
            List<ThumbsUp> thumbsUps = thumbsUpMapper.selectList(new LambdaQueryWrapper<ThumbsUp>()
                    .eq(ThumbsUp::getThumbsUpUserAid, currentLoginUserAid)
                    .eq(ThumbsUp::getThumbsUpedAid, dynamic.getAid())
                    .eq(ThumbsUp::getType, "动态")
                    .or()
                    .eq(ThumbsUp::getThumbsUpUserAid, currentLoginUserAid)
                    .eq(ThumbsUp::getThumbsUpedAid, dynamic.getAid())
                    .eq(ThumbsUp::getType, "笔记")
            );
//            System.out.println("是否点赞");
//            System.out.println(thumbsUps.size());
            if(thumbsUps.size() > 0){
                map.put("isLike",true);
            }else {
                map.put("isLike",false);
            }

            // 获取随机高度
            // 创建一个 Random 对象
            Random random = new Random();
            // 生成一个范围在 200 到 300 之间的随机整数
            int randomHeight = random.nextInt(101) + 200;
            map.put("imageHeight",randomHeight);

            map.put("title", dynamic.getDynamicName().length() > 26 ? dynamic.getDynamicName().substring(0,24) + "..." : dynamic.getDynamicName());
            // 查询作者头像
            User user = userMapper.selectById(dynamic.getUserAid());
            map.put("authorAvatar", user.getAvatar());
            map.put("authorUserName", user.getName());
            map.put("likesNum", dynamic.getDianZanNum());
            // 是图片还是视频（图片false,视频true）
            if (dynamic.getDynamicVideo() == null || dynamic.getDynamicVideo().isEmpty()) {
                map.put("isVedio", false);
            } else {
                map.put("isVedio", true);
            }
            // 视频封面（如果该条帖子是图片没有视频，那么这一项就为‘’）
            map.put("vedioCover", dynamic.getMedioType().equals("image") ? "" : dynamic.getDynamicCover());
            result.add(map);
        }
        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper getFoodsList(Integer currentLoginUserAid, String travelMode) {

        /* 获取露营动态列表（按照发布时间获取最近最新的点赞量最多的倒序，获取20条） */
        List<Dynamic> foodsList = dynamicMapper.selectList(new LambdaQueryWrapper<Dynamic>()
                .eq(Dynamic::getDynamicType, "美食")
                .eq(Dynamic::getDynamicArea, travelMode.equals("境内游") ? "国内" : "国外")
                .ne(Dynamic::getUserAid, 6)
                .ne(Dynamic::getUserAid, 7)
                .eq(Dynamic::getIsDraft,false)
                .eq(Dynamic::getIsRelease,true)
                .orderByDesc(Dynamic::getUpdateTime)
                .orderByDesc(Dynamic::getDianZanNum)
                .last("limit 20")
        );

        // 返回数据
        return getDynamicListFunc(foodsList,currentLoginUserAid);
    }

    @Override
    public ResponseWrapper getHomestayList(Integer currenLoginUserAid, String travelMode) {

        /* 获取露营动态列表（按照发布时间获取最近最新的点赞量最多的倒序，获取20条） */
        List<Dynamic> homestayList = dynamicMapper.selectList(new LambdaQueryWrapper<Dynamic>()
                .eq(Dynamic::getDynamicType, "民宿")
                .eq(Dynamic::getDynamicArea, travelMode.equals("境内游") ? "国内" : "国外")
                .ne(Dynamic::getUserAid, 6)
                .ne(Dynamic::getUserAid, 7)
                .eq(Dynamic::getIsDraft,false)
                .eq(Dynamic::getIsRelease,true)
                .orderByDesc(Dynamic::getUpdateTime)
                .orderByDesc(Dynamic::getDianZanNum)
                .last("limit 20")
        );

        // 返回数据
        return getDynamicListFunc(homestayList,currenLoginUserAid);
    }

    @Override
    public ResponseWrapper getActivitiesList(Integer currenLoginUserAid, String travelMode) {
        /* 获取露营动态列表（按照发布时间获取最近最新的点赞量最多的倒序，获取20条） */
        List<Dynamic> homestayList = dynamicMapper.selectList(new LambdaQueryWrapper<Dynamic>()
                .eq(Dynamic::getDynamicType, "活动")
                .eq(Dynamic::getDynamicArea, travelMode.equals("境内游") ? "国内" : "国外")
                .ne(Dynamic::getUserAid, 6)
                .ne(Dynamic::getUserAid, 7)
                .eq(Dynamic::getIsDraft,false)
                .eq(Dynamic::getIsRelease,true)
                .orderByDesc(Dynamic::getUpdateTime)
                .orderByDesc(Dynamic::getDianZanNum)
                .last("limit 20")
        );

        // 返回数据
        return getDynamicListFunc(homestayList,currenLoginUserAid);
    }

    @Override
    public ResponseWrapper getCityList() {

        try {
            List<String> citiesInCurrentProvince = GaoDeTool.getCitiesInCurrentProvince();

            return ResponseWrapper.markSuccess(citiesInCurrentProvince);
        } catch (IOException e) {
            e.printStackTrace();
            // 如果出现异常，返回一个空的城市列表
            return ResponseWrapper.markSuccess(new ArrayList<>());
        }
    }

    @Override
    public ResponseWrapper saveDraft(Integer userAid, SaveDraftParam param) {

        Dynamic dynamic = new Dynamic();
        // 设置动态名称（标题），若标题为空则设置为空格
        dynamic.setDynamicName(param.getTitle().isEmpty()? " " : param.getTitle());
        // 设置动态类型，根据 noteTypeValue 映射类型名称
        dynamic.setDynamicType(getDynamicTypeFromNoteTypeValue(param.getNoteTypeValue()));
        // 设置动态图片相关内容
        dynamic.setDynamicImgs(getDynamicImgs(param.getMediaUrls()));
        dynamic.setDynamicContent(param.getContent());
        dynamic.setDianZanNum(0);
        dynamic.setCommentNum(0);
        dynamic.setUserAid(userAid);
        if (param.getTravelFieldValue().equals("境内游")){
            dynamic.setDynamicArea("国内");
        }else {
            dynamic.setDynamicArea("国外");
        }
        // 设置动态视频和封面相关内容
        setDynamicVideoAndCover(param.getMediaUrls(), dynamic);
        // 设置发布地址
        dynamic.setReleaseAddress(getReleaseAddress(param.getLaberAddress()));
        String location = param.getLocation();
        if (location.contains(",")){
            String[] split = location.split(",");
            dynamic.setReleaseAddressPosition(split[0] + ";" + split[1]);
        }else {
            dynamic.setReleaseAddressPosition(null);
        }

        // 设置可见范围
        dynamic.setSeeField(param.getSeeField());
        dynamic.setIsDraft(true);
        dynamic.setIsRelease(false);
        // 设置艾特用户的相关信息
        dynamic.setAiteUserAid(getAiteUserAids(param.getAiteUsers()));

        int insert = dynamicMapper.insert(dynamic);
        return insert > 0? ResponseWrapper.markSuccess() : ResponseWrapper.markError();
    }

    private String getDynamicTypeFromNoteTypeValue(Integer noteTypeValue) {
        switch (noteTypeValue) {
            case 0:
                return "露营";
            case 1:
                return "美食";
            case 2:
                return "民宿";
            default:
                return "活动";
        }
    }

    private String getDynamicImgs(List<MediaParam> mediaUrls) {
        System.out.println("图片：");
        System.out.println(JSONUtil.toJsonStr(mediaUrls));
        if (mediaUrls.isEmpty()) {
            return "";
        }
        if (mediaUrls.get(0).getFileType().equals("image")) {
            return mediaUrls.stream()
                    .map(MediaParam::getUrl)
                    .collect(Collectors.joining(";"));
        }
        return "";
    }

    private void setDynamicVideoAndCover(List<MediaParam> mediaUrls, Dynamic dynamic) {
        System.out.println("视频地址和封面：");
        System.out.println(mediaUrls);
        if (mediaUrls.isEmpty() || mediaUrls.equals("")) {
            dynamic.setDynamicVideo("");
            dynamic.setDynamicCover("");
            return;
        }
        if (mediaUrls.get(0).getFileType().equals("image")) {
            dynamic.setDynamicVideo("");
            dynamic.setDynamicCover("");
            dynamic.setMedioType("image");
        } else {
            dynamic.setDynamicVideo(mediaUrls.get(0).getUrl());
            dynamic.setDynamicCover(mediaUrls.get(0).getCover());
            dynamic.setMedioType("video");
        }
    }

    private String getReleaseAddress(String laberAddress) {
        return laberAddress.isEmpty() || laberAddress.equals("标记地点")? "" : laberAddress;
    }

    private String getAiteUserAids(List<AiteUser> aiteUsers) {
        if (aiteUsers.isEmpty()) {
            return "";
        }
        StringBuilder aiteUserAidsBuilder = new StringBuilder();
        for (AiteUser aiteUser : aiteUsers) {
            aiteUserAidsBuilder.append(aiteUser.getUserAid()).append(";");
        }
        return aiteUserAidsBuilder.substring(0, aiteUserAidsBuilder.length() - 1);
    }

    @Override
    public ResponseWrapper getTopicAndUsers(Integer userAid) {
        HashMap<String, Object> result = new HashMap<>();

        // 获取话题列表
        List<HashMap<String, Object>> topicList = getTopicList(userAid);
        result.put("topicList", topicList);

        // 获取用户列表
        List<HashMap<String, Object>> userList = getUserList(userAid);
        result.put("userList", userList);

        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper releaseNote(Integer userAidByToken, ReleaseNoteParam param) {


        Dynamic dynamic = new Dynamic();
        dynamic.setDynamicName(param.getTitle());
        // 设置动态类型，根据 noteTypeValue 映射类型名称
        dynamic.setDynamicType(getDynamicTypeFromNoteTypeValue(param.getNoteTypeValue()));
        // 设置动态图片相关内容
        dynamic.setDynamicImgs(getDynamicImgs(param.getMediaUrls()));
        dynamic.setDynamicContent(param.getContent().trim());
        dynamic.setDianZanNum(0);
        dynamic.setCommentNum(0);
        dynamic.setUserAid(userAidByToken);
        if (param.getTravelFieldValue().equals("境内游")){
            dynamic.setDynamicArea("国内");
        }else {
            dynamic.setDynamicArea("国外");
        }
        // 设置动态视频和封面相关内容
        setDynamicVideoAndCover(param.getMediaUrls(), dynamic);
        // 设置发布地址
        dynamic.setReleaseAddress(getReleaseAddress(param.getLaberAddress()));
        String location = param.getLocation();
        if (location.contains(",")){
            String[] split = location.split(",");
            dynamic.setReleaseAddressPosition(split[0] + ";" + split[1]);
        }else {
            dynamic.setReleaseAddressPosition(null);
        }

        // 设置可见范围
        dynamic.setSeeField(param.getSeeField());
        dynamic.setIsDraft(false);
        dynamic.setIsRelease(true);
        // 设置艾特用户的相关信息
        dynamic.setAiteUserAid(getAiteUserAids(param.getAiteUsers()));
        if (param.getTopicList().isEmpty()){
            dynamic.setTopicAid(null);
        }else {
            StringBuilder topicAids = new StringBuilder();
            for (TopicParam topicParam : param.getTopicList()) {
                topicAids.append(topicParam.getTopicAid()).append(";");
            }
            dynamic.setTopicAid(topicAids.substring(0,topicAids.length()-1));
        }
        int insert = dynamicMapper.insert(dynamic);
        return insert > 0? ResponseWrapper.markSuccess() : ResponseWrapper.markError();
    }

    @Override
    public ResponseWrapper getNoteDetailInfos(Integer userAidByToken, Integer noteAid) {

        // 返回结果
        HashMap<String, Object> result = new HashMap<>();

        // 获取笔记的作者信息
        Dynamic dynamic = dynamicMapper.selectById(noteAid);
        Integer authorAid = dynamic.getUserAid();
        result.put("authorAid",authorAid);
        User user = userMapper.selectById(authorAid);

        // 当前登录的用户是否关注了作者
        List<UserFollow> userFollows = userFollowMapper.selectList(new LambdaQueryWrapper<UserFollow>()
                .eq(UserFollow::getFollowerAid, userAidByToken)
                .eq(UserFollow::getFolloweredAid, authorAid)
                .eq(UserFollow::getFollowerType, "用户")
        );
        if (!userFollows.isEmpty()){
            result.put("isGuanzhuAuthor",true);
        }else {
            result.put("isGuanzhuAuthor",false);
        }

        // 查询这条笔记是否是视频(如果是视频就查询videoUrl地址；如果不是videoUrl为空字符串)
        result.put("isVedio", dynamic.getMedioType().equals("video"));
        result.put("videoUrl",dynamic.getMedioType().equals("video") ? (dynamic.getDynamicVideo() == null ? "" : dynamic.getDynamicVideo()) : "");

        // 查询所有评论
        List<Comment> allComments = commentMapper.selectList(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getCommentType, "笔记")
                .eq(Comment::getNoteAid, noteAid)
//                .orderByDesc(Comment::getLikeCount) // 先按照点赞次数降序排列
                .orderByDesc(Comment::getCreateTime));

        /*
         allComments中把parentCommentId为null的筛选出来
          使用Stream API筛选出parentCommentId为null的评论
        */
        List<Comment> topLevelComments = allComments.stream()
                .filter(comment -> comment.getParentCommentId() == null)
                .collect(Collectors.toList());

        // 除去一级评论以外的其他评论
        List<Comment> otherLevelComments = allComments.stream()
                .filter(comment -> comment.getParentCommentId() != null)
                .collect(Collectors.toList());
        for (Comment topLevelComment : topLevelComments) {
            ArrayList<Comment> comments = new ArrayList<>();
            for (Comment otherLevelComment : otherLevelComments) {
                if (otherLevelComment.getRootCommentAid().equals(topLevelComment.getAid())){
                    comments.add(otherLevelComment);
                }
            }
            topLevelComment.setReplyList(comments);
        }

        ArrayList<HashMap<String, Object>> hashMaps = new ArrayList<>();
        for (Comment rootComment : topLevelComments) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("aid",rootComment.getAid());
            User user1 = userMapper.selectById(rootComment.getUserAid());
            map.put("commentUserAvatar",user1.getAvatar());
            map.put("commentUserAid",user1.getAid());
            map.put("commentUsername",user1.getName());
            map.put("commentContent",rootComment.getCommentName());
            map.put("commentTime", ToolForDateTime.LocalDateTimeToString(rootComment.getCreateTime()));
            map.put("likeCount",rootComment.getLikeCount());

            // 当前登录用户是否点赞了这条评论
            List<ThumbsUp> thumbsUps = thumbsUpMapper.selectList(new LambdaQueryWrapper<ThumbsUp>()
                    .eq(ThumbsUp::getThumbsUpUserAid, userAidByToken)
                    .eq(ThumbsUp::getThumbsUpedAid, rootComment.getAid())
                    .eq(ThumbsUp::getType, "评论")
            );

            if (thumbsUps.size() > 0){
                map.put("isLikeThisComment",true);
            }else {
                map.put("isLikeThisComment",false);
            }
            ArrayList<HashMap<String, Object>> hashMaps1 = new ArrayList<>();
            if (rootComment.getReplyList().size() > 0){
                List<Comment> replyList = rootComment.getReplyList();
                for (Comment comment : replyList) {
                    HashMap<String, Object> map1 = new HashMap<>();
                    map1.put("aid",comment.getAid());
                    User user2 = userMapper.selectById(comment.getUserAid());
                    map1.put("replyAvatar",user2.getAvatar());
                    map1.put("replyUserAid",user2.getAid());
                    map1.put("replyUserName",user2.getName());
                    map1.put("replyContent",comment.getCommentName());
                    map1.put("replyTime",ToolForDateTime.LocalDateTimeToString(comment.getCreateTime()));
                    map1.put("likeCount",comment.getLikeCount());
                    Long parentCommentId = comment.getParentCommentId();
                    Comment comment1 = commentMapper.selectById(parentCommentId);
                    Long userAid = comment1.getUserAid();
                    User user3 = userMapper.selectById(userAid);
                    map1.put("replayWhichUserAid",user3.getAid());
                    map1.put("replayWhichUser",user3.getName());
                    // 当前登录用户是否点赞了这条评论
                    List<ThumbsUp> childCommentThumbs = thumbsUpMapper.selectList(new LambdaQueryWrapper<ThumbsUp>()
                            .eq(ThumbsUp::getThumbsUpUserAid, userAidByToken)
                            .eq(ThumbsUp::getThumbsUpedAid, comment.getAid())
                            .eq(ThumbsUp::getType, "评论")
                    );
                    if (childCommentThumbs.size() > 0){
                        map1.put("isLikeThisComment",true);
                    }else {
                        map1.put("isLikeThisComment",false);
                    }
                    hashMaps1.add(map1);
                }
            }
            map.put("replyList",hashMaps1);
            hashMaps.add(map);
        }

        result.put("commentList", hashMaps);

        // 评论数量
        result.put("commentCount",allComments.size());

        // 笔记发布日期
        result.put("releaseDate",ToolForDateTime.LocalDateTimeToString(dynamic.getUpdateTime()));

        // @用户列表
        ArrayList<HashMap<String,Object>> aiteUsers = new ArrayList<>();
        if (dynamic.getAiteUserAid() == null || dynamic.getAiteUserAid().equals("")){
            result.put("aiteUsers",aiteUsers);
        }else {
            String userAids = dynamic.getAiteUserAid();
            if (userAids.contains(";")){
                String[] split = userAids.split(";");
                for (String s : split) {
                    User user1 = userMapper.selectById(Integer.parseInt(s));
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("userAid", user1.getAid());
                    map.put("aitaUser","@" + user1.getName());
                    aiteUsers.add(map);
                }
            }else {
                User user1 = userMapper.selectById(userAids);
                HashMap<String, Object> map = new HashMap<>();
                map.put("userAid", user1.getAid());
                map.put("aitaUser","@" + user1.getName());
                aiteUsers.add(map);
            }
            result.put("aiteUsers",aiteUsers);
        }

        // 话题列表
        List<HashMap<String,Object>> topicList = new ArrayList<>();
        if (dynamic.getTopicAid() == null || dynamic.getTopicAid().equals("")){
            result.put("topicList",topicList);
        }else {
            String topicAid = dynamic.getTopicAid();
            if (topicAid.contains(";")){
                String[] split = topicAid.split(";");
                for (String s : split) {
                    Topic topic = topicMapper.selectById(Integer.parseInt(s));
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("topicAid",topic.getAid());
                    map.put("topicName",topic.getName().contains("#") ? topic.getName() : "#" + topic.getName());
                    topicList.add(map);
                }
            }else {
                Topic topic = topicMapper.selectById(topicAid);
                HashMap<String, Object> map = new HashMap<>();
                map.put("topicAid",topic.getAid());
                map.put("topicName",topic.getName().contains("#") ? topic.getName() : "#" + topic.getName());
                topicList.add(map);
            }
            result.put("topicList",topicList);
        }

        // 笔记内容
        result.put("noteContent",dynamic.getDynamicContent());

        // 笔记名称
        result.put("noteTitle",dynamic.getDynamicName());

        // 当前登录用户是否收藏了这篇笔记
        List<Collect> notes = collectMapper.selectList(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getCollectType, "笔记")
                .eq(Collect::getUserAid, userAidByToken)
                .eq(Collect::getCollectAid, noteAid)
        );
        if (notes.size() > 0){
            result.put("isCollect",true);
        }else {
            result.put("isCollect",false);
        }

        // 如果这篇笔记是图片组成的，不是一个视频，那么图片地址数组
        ArrayList<String> imgs = new ArrayList<>();
        if (dynamic.getMedioType().equals("image")){
            if (dynamic.getDynamicImgs() == null || dynamic.getDynamicImgs().equals("")){
                result.put("noteImgs",imgs);
            }else {
                String dynamicImgs = dynamic.getDynamicImgs();
                if (dynamicImgs.contains(";")){
                    String[] split = dynamicImgs.split(";");
                    imgs.addAll(Arrays.asList(split));
                }else {
                    imgs.add(dynamicImgs);
                }
                result.put("noteImgs",imgs);
            }
        }else {
            result.put("noteImgs",imgs);
        }

        // 这篇笔记有多少用户收藏
        List<Collect> collectnotes = collectMapper.selectList(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getCollectType, "笔记")
                .eq(Collect::getCollectAid, noteAid)
        );
        result.put("collectNum",collectnotes.size());

        // 当前登录用户是否点赞了这篇笔记
        List<ThumbsUp> thumbsUps = thumbsUpMapper.selectList(new LambdaQueryWrapper<ThumbsUp>()
                .eq(ThumbsUp::getThumbsUpUserAid, userAidByToken)
                .eq(ThumbsUp::getThumbsUpedAid, noteAid)
                .eq(ThumbsUp::getType, "动态")
                .eq(ThumbsUp::getHandType, "heart-filled")
                .or()
                .eq(ThumbsUp::getThumbsUpUserAid, userAidByToken)
                .eq(ThumbsUp::getThumbsUpedAid, noteAid)
                .eq(ThumbsUp::getType, "笔记")
                .eq(ThumbsUp::getHandType, "hand-up-filled"));
//        System.out.println("笔记aid：" + noteAid);
//        System.out.println("是否点赞：");
//        System.out.println(JSONUtil.toJsonStr(thumbsUps));
        if (thumbsUps.size() > 0){
            result.put("isLike",true);
        }else {
            result.put("isLike",false);
        }


        // 这条笔记的点赞数量
        result.put("noteLikesNum",dynamic.getDianZanNum());

        // 笔记的作者名字
        result.put("authorName",user.getName());

        // 笔记的作者头像
        result.put("authorAvatar",user.getAvatar());

        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper thumbsUpThisComment(Integer userAidByToken, Integer commentAid) {

        // 先查询，如果查询到就是已经点赞了，现在取消点赞；如果没查询到就是还没点赞，现在要点赞
        List<ThumbsUp> thumbsUps = thumbsUpMapper.selectList(new LambdaQueryWrapper<ThumbsUp>()
                .eq(ThumbsUp::getThumbsUpUserAid, userAidByToken)
                .eq(ThumbsUp::getThumbsUpedAid, commentAid)
                .eq(ThumbsUp::getType, "评论")
        );
        // 评论表的点赞数量-1
        Comment comment = commentMapper.selectById(commentAid);
        if (thumbsUps.size() > 0){
            for (ThumbsUp thumbsUp : thumbsUps) {
                thumbsUpMapper.deleteById(thumbsUp);
            }
            comment.setLikeCount(comment.getLikeCount() > 0 ? comment.getLikeCount() - 1 : 0);
            commentMapper.updateById(comment);
        }else {
            // 点赞，comment的点赞数量+！，新增thumbs_up表里面那一条数据
            comment.setLikeCount(comment.getLikeCount() + 1);
            commentMapper.updateById(comment);
            thumbsUpMapper.insert(new ThumbsUp(){{
                setThumbsUpUserAid(userAidByToken);
                setThumbsUpedAid(commentAid);
                setType("评论");
                setHandType("hand-up-filled");
                setHandColor("red");
            }});
        }
        return ResponseWrapper.markSuccess();
    }

    @Override
    public ResponseWrapper thumbsUpNote(Integer userAidByToken, Integer noteAid) {

        Dynamic dynamic = dynamicMapper.selectById(noteAid);
        List<ThumbsUp> thumbsUps = thumbsUpMapper.selectList(new LambdaQueryWrapper<ThumbsUp>()
                .eq(ThumbsUp::getThumbsUpedAid, noteAid)
                .eq(ThumbsUp::getThumbsUpUserAid, userAidByToken)
                .eq(ThumbsUp::getType, "动态")
                .or()
                .eq(ThumbsUp::getThumbsUpedAid, noteAid)
                .eq(ThumbsUp::getThumbsUpUserAid, userAidByToken)
                .eq(ThumbsUp::getType, "笔记")
        );
        if (thumbsUps.size() > 0){
            // 说明这篇笔记或者动态已经被当前登录的用户点赞过了，现在执行取消点赞操作
            dynamic.setDianZanNum(dynamic.getDianZanNum() > 0 ? dynamic.getDianZanNum() - 1 : 0);
            dynamicMapper.updateById(dynamic);
            for (ThumbsUp thumbsUp : thumbsUps) {
                thumbsUpMapper.deleteById(thumbsUp);
            }
        }else {
            dynamic.setDianZanNum(dynamic.getDianZanNum() + 1);
            dynamicMapper.updateById(dynamic);
            thumbsUpMapper.insert(new ThumbsUp(){{
                setThumbsUpUserAid(userAidByToken);
                setThumbsUpedAid(noteAid);
                setType("笔记");
                setHandType("heart-filled");
                setHandColor("red");
            }});
        }
        return ResponseWrapper.markSuccess();
    }

    @Override
    public ResponseWrapper collectNote(Integer userAidByToken, Integer noteAid) {

        List<Collect> collects = collectMapper.selectList(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getUserAid, userAidByToken)
                .eq(Collect::getCollectAid, noteAid)
                .eq(Collect::getCollectType, "动态")
                .or()
                .eq(Collect::getUserAid, userAidByToken)
                .eq(Collect::getCollectAid, noteAid)
                .eq(Collect::getCollectType, "笔记")
        );
        Dynamic dynamic = dynamicMapper.selectById(noteAid);
        User user = userMapper.selectById(userAidByToken);
        if (collects.size() > 0){
            dynamic.setCollectNum(dynamic.getCollectNum().equals(0) ? 0 : dynamic.getCollectNum() - 1);
            user.setCollectNum(user.getCollectNum().equals(0) ? 0 : user.getCollectNum() - 1);
            for (Collect collect : collects) {
                collectMapper.deleteById(collect);
                userMapper.updateById(user);
            }
        }else {
            dynamic.setCollectNum(dynamic.getCollectNum() + 1);
            user.setCollectNum(user.getCollectNum() + 1);
            collectMapper.insert(new Collect(){{
                setCollectType("笔记");
                setUserAid(Long.valueOf(userAidByToken));
                setCollectAid(Long.valueOf(noteAid));
            }});
            userMapper.updateById(user);
        }
        dynamicMapper.updateById(dynamic);
        return ResponseWrapper.markSuccess();
    }

    @Override
    public ResponseWrapper guanzhuAuthor(Integer userAidByToken, Integer authorAid) {

        List<UserFollow> userFollows = userFollowMapper.selectList(new LambdaQueryWrapper<UserFollow>()
                .eq(UserFollow::getFollowerAid, userAidByToken)
                .eq(UserFollow::getFolloweredAid, authorAid)
                .eq(UserFollow::getFollowerType, "用户")
        );
        User user = userMapper.selectById(userAidByToken);
        User author = userMapper.selectById(authorAid);
        if (userFollows.size() > 0){
            for (UserFollow userFollow : userFollows) {
                userFollowMapper.deleteById(userFollow);
            }
            user.setGuanzhuNum(user.getGuanzhuNum().equals(0) ? 0 : user.getGuanzhuNum() - 1);
            author.setFans(author.getFans().equals(0) ? 0 : author.getFans() - 1);
        }else {
            userFollowMapper.insert(new UserFollow(){{
                setFollowerAid(userAidByToken);
                setFolloweredAid(authorAid);
                setFollowerType("用户");
            }});
            user.setGuanzhuNum(user.getGuanzhuNum() + 1);
            author.setFans(author.getFans() + 1);
        }
        userMapper.updateById(user);
        userMapper.updateById(author);
        return ResponseWrapper.markSuccess();
    }

    @Override
    public ResponseWrapper sendCommentContent(Integer userAidByToken, SendComment param) {

        Comment comment = new Comment();
        comment.setCommentName(param.getCommentInput());
        comment.setUserAid(userAidByToken.longValue());
        comment.setCommentType("笔记");
        comment.setParentCommentId(
                param.getReplyCommentId() == null
                        ?
                null : param.getReplyCommentId().longValue());
        comment.setLikeCount(0);
        comment.setNoteAid(param.getNoteAid().longValue());
        if (param.getReplyCommentId() == null){
            comment.setRootCommentAid(null);
        }else {
            Comment comment1 = commentMapper.selectById(param.getReplyCommentId());
            comment.setRootCommentAid(comment1.getRootCommentAid() == null ? comment1.getAid() : comment1.getRootCommentAid());
        }
        commentMapper.insert(comment);
        Dynamic dynamic = dynamicMapper.selectById(param.getNoteAid());
        dynamic.setCommentNum(dynamic.getCommentNum() + 1);
        dynamicMapper.updateById(dynamic);
        return ResponseWrapper.markSuccess();
    }

    @Override
    public ResponseWrapper getNearList(Integer currentLoginUserAid, String travelMode) {
        /* 获取所有的标记地点的动态列表，返回给前端，让前端去筛选距离 */
        List<Dynamic> nearList = dynamicMapper.selectList(new LambdaQueryWrapper<Dynamic>()
//                .eq(Dynamic::getDynamicType, "附近")
                .eq(Dynamic::getDynamicArea, travelMode.equals("境内游") ? "国内" : "国外")
                .ne(Dynamic::getUserAid, 6)
                .ne(Dynamic::getUserAid, 7)
                .eq(Dynamic::getIsDraft,false)
                .eq(Dynamic::getIsRelease,true)
                .isNotNull(Dynamic::getReleaseAddressPosition)
                .orderByDesc(Dynamic::getUpdateTime)
                .orderByDesc(Dynamic::getDianZanNum)
//                .last("limit 20")
                .or()
                .eq(Dynamic::getDynamicArea, travelMode.equals("境内游") ? "国内" : "国外")
                .ne(Dynamic::getUserAid, 6)
                .ne(Dynamic::getUserAid, 7)
                .eq(Dynamic::getIsDraft,false)
                .eq(Dynamic::getIsRelease,true)
                .eq(Dynamic::getReleaseAddressPosition,"")
                .orderByDesc(Dynamic::getUpdateTime)
                .orderByDesc(Dynamic::getDianZanNum)
        );

        // 返回数据
//        return getDynamicListFunc(nearList,currentLoginUserAid);
        return getNearDynamicListFunc(nearList,currentLoginUserAid);

    }

    @Override
    public ResponseWrapper deleteDynamic(Integer userAidByToken, DeleteDynamicByNoteAidParam param) {

        Dynamic dynamic = dynamicMapper.selectById(param.getNoteAid());
        if (dynamic != null){
            int i = dynamicMapper.deleteById(dynamic);
            if (i > 0){
                return ResponseWrapper.markSuccess();
            }else {
                return ResponseWrapper.markError();
            }
        }else {
            return ResponseWrapper.markError();
        }
    }

    private ResponseWrapper getNearDynamicListFunc(List<Dynamic> campingList, Integer currentLoginUserAid) {

        ArrayList<HashMap<String, Object>> result = new ArrayList<>();
        for (Dynamic dynamic : campingList) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("aid", dynamic.getAid());
            String dynamicVideo = dynamic.getDynamicVideo()!= null? dynamic.getDynamicVideo() : "";
            String dynamicCover = dynamic.getDynamicCover()!= null? dynamic.getDynamicCover() : "";

            if (dynamic.getMedioType().equals("image")) {
                if(dynamic.getDynamicImgs().equals("") || dynamic.getDynamicImgs() == null){
                    map.put("url", "");
                }else {
                    String dynamicImgs = dynamic.getDynamicImgs();
                    if(dynamicImgs.contains(";")){
                        String[] split = dynamicImgs.split(";");
                        map.put("url", split[0]);
                    }else {
                        map.put("url", dynamicImgs);
                    }
                }
            } else {
                map.put("url", dynamicVideo == null ? "" : dynamicVideo);
            }
//            System.out.println("当前登录用户：" + currentLoginUserAid);
            // 当前登录用户是否点赞这篇动态
            List<ThumbsUp> thumbsUps = thumbsUpMapper.selectList(new LambdaQueryWrapper<ThumbsUp>()
                    .eq(ThumbsUp::getThumbsUpUserAid, currentLoginUserAid)
                    .eq(ThumbsUp::getThumbsUpedAid, dynamic.getAid())
                    .eq(ThumbsUp::getType, "动态")
                    .or()
                    .eq(ThumbsUp::getThumbsUpUserAid, currentLoginUserAid)
                    .eq(ThumbsUp::getThumbsUpedAid, dynamic.getAid())
                    .eq(ThumbsUp::getType, "笔记")
            );
//            System.out.println("是否点赞");
//            System.out.println(thumbsUps.size());
            if(thumbsUps.size() > 0){
                map.put("isLike",true);
            }else {
                map.put("isLike",false);
            }

            // 获取随机高度
            // 创建一个 Random 对象
            Random random = new Random();
            // 生成一个范围在 200 到 300 之间的随机整数
            int randomHeight = random.nextInt(101) + 200;
            map.put("imageHeight",randomHeight);

            map.put("title", dynamic.getDynamicName().length() > 26 ? dynamic.getDynamicName().substring(0,24) + "..." : dynamic.getDynamicName());
            // 查询作者头像
            User user = userMapper.selectById(dynamic.getUserAid());
            map.put("authorAvatar", user.getAvatar());
            map.put("authorUserName", user.getName());
            map.put("likesNum", dynamic.getDianZanNum());
            // 是图片还是视频（图片false,视频true）
            if (dynamic.getDynamicVideo() == null || dynamic.getDynamicVideo().isEmpty()) {
                map.put("isVedio", false);
            } else {
                map.put("isVedio", true);
            }
            // 视频封面（如果该条帖子是图片没有视频，那么这一项就为‘’）
            map.put("vedioCover", dynamic.getMedioType().equals("image") ? "" : dynamic.getDynamicCover());

            // 返回标记地点 的经纬度
            map.put("pos", dynamic.getReleaseAddressPosition());

            result.add(map);
        }
        return ResponseWrapper.markSuccess(result);
    }


    private static List<Comment> getChildrenComments(Map<Long, List<Comment>> commentMap, Long parentId, int level) {
        List<Comment> children = commentMap.getOrDefault(parentId, new ArrayList<>());
        List<Comment> result = new ArrayList<>();
        for (Comment child : children) {
            // 递归获取子评论
            List<Comment> deeperChildren = getChildrenComments(commentMap, child.getAid(), level + 1);
            child.setReplyList(deeperChildren);
            result.add(child);
        }
        return result;
    }




    private List<HashMap<String, Object>> getTopicList(Integer userAid) {
        List<TopicUser> topicUsers = topicUserMapper.selectList(new LambdaQueryWrapper<TopicUser>()
                .orderByDesc(TopicUser::getAid)
                .last("limit 10"));

//        if (topicUsers.isEmpty()) {
//            return getTopTopics().stream()
//                    .map(this::buildTopicMap)
//                    .collect(Collectors.toList());
//        }

        return topicUsers.stream()
                .limit(10)
                .map(topicUser -> buildTopicMap(topicMapper.selectById(topicUser.getTopicAid())))
                .collect(Collectors.toList());
    }

    private List<Topic> getTopTopics() {
        return topicMapper.selectList(new LambdaQueryWrapper<Topic>()
                .orderByDesc(Topic::getJoinCount)
                .last("limit " + 10));
    }

    private HashMap<String, Object> buildTopicMap(Topic topic) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("topicAid", topic.getAid());
        map.put("topicName", topic.getName().contains("#")? topic.getName() : "#" + topic.getName());
        map.put("selected", false);
        return map;
    }

    private List<HashMap<String, Object>> getUserList(Integer userAid) {
        List<UserFollow> userFollows = userFollowMapper.selectList(new LambdaQueryWrapper<UserFollow>()
                .eq(UserFollow::getFollowerAid, userAid)
                .last("limit 10"));

        if (userFollows.isEmpty()) {
            return getUserByFansExcludingSelf(userAid).stream()
                    .map(this::buildUserMap)
                    .collect(Collectors.toList());
        }

        return userFollows.stream()
                .limit(10)
                .map(userFollow -> buildUserMap(userMapper.selectById(userFollow.getFolloweredAid())))
                .collect(Collectors.toList());
    }

    private List<User> getUserByFansExcludingSelf(Integer userAid) {
        return userMapper.selectList(new LambdaQueryWrapper<User>()
                .orderByDesc(User::getFans)
                .ne(User::getAid, userAid)
                .last("limit " + 10));
    }

    private HashMap<String, Object> buildUserMap(User user) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userAid", user.getAid());
        map.put("userName", "@" + user.getName());
        map.put("selected", false);
        return map;
    }
}
